package com.xinghai.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author xinghai
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }
    public static final String dateTimeByDate(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTimeMonth(Date date)
    {
        return parseDateToStr(YYYY_MM, date);
    }


    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static void main(String[] args) {
        System.out.println("当天0点0分0秒的时间:"+getMonthLastDay("2024-11"));
        System.out.println("当天0点0分0秒的时间:"+getLastMonthMinDate());
        System.out.println("当天0点0分0秒的时间:"+getMonthStartDay("2024-11"));
        System.out.println("当天0点0分0秒的时间:"+getLastMonthStartDay("2024-11"));
    }
    public static String getWeekStartData(String date){
        /**
         * 转为calendar格式
         * calendar.get(Calendar.MONTH)+1  calendar中的月份以0开头
         * Calendar.DAY_OF_WEEK 当前日期是所在周的第几天（以周日为一周的第一天）
         * Calendar.DATE 当前日期是几号
         *  */
        Date dataTime = DateUtils.parseDate(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dataTime);

        // 如果是周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }
        // 获取当前日期是当周的第i天
        int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;

        // 获取当前日期所在周的第一天
        calendar.add(Calendar.DATE , -i+1);
        return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
    }
    public static String getLastWeekStartData(String date){
        /**
         * 转为calendar格式
         * calendar.get(Calendar.MONTH)+1  calendar中的月份以0开头
         * Calendar.DAY_OF_WEEK 当前日期是所在周的第几天（以周日为一周的第一天）
         * Calendar.DATE 当前日期是几号
         *  */
        Date dataTime = DateUtils.parseDate(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dataTime);
        // 如果是周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }
        // 获取当前日期是当周的第i天
        int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        // 获取当前日期所在周的第一天
        calendar.add(Calendar.DATE , -i+1);
        calendar.add(Calendar.DATE , 7);
        return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
    }
    public static List<String> getWeekData(Date dataTime){
        /**
         * 转为calendar格式
         * calendar.get(Calendar.MONTH)+1  calendar中的月份以0开头
         * Calendar.DAY_OF_WEEK 当前日期是所在周的第几天（以周日为一周的第一天）
         * Calendar.DATE 当前日期是几号
         *  */
        List<String> week = new ArrayList<String>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dataTime);

        // 如果是周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }
        // 获取当前日期是当周的第i天
        int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;

        // 获取当前日期所在周的第一天
        calendar.add(Calendar.DATE , -i+1);
        System.out.println("日期所在周的周一是：" + new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        for (int j = 0; j < 7; j++) {
            if(j >0){
                calendar.add(Calendar.DATE , 1);
            }
            week.add(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        }
        return week;
    }

    public static Date getMonthStartDay(String dt) {
        String[] split = dt.split("-");
        LocalDate first = LocalDate.of(Integer.parseInt(split[0]),Integer.parseInt(split[1]),1);
        return DateUtils.toDate(first);
    }

    public static Date getLastMonthStartDay(String dt) {
        String[] split = dt.split("-");
        LocalDate first = LocalDate.of(Integer.parseInt(split[0]),Integer.parseInt(split[1]),1);
        return DateUtils.toDate(first.plusMonths(1));
    }
    //当天0点0分0秒的时间
    public static Date getNowDateStart() {
        //1.获取当前时间
        LocalDate today = LocalDate.now();
        LocalDateTime todayMidnight = LocalDateTime.of(today, LocalTime.MIN);
        return DateUtils.toDate(todayMidnight);
    }

    /**
     * 获取本月第一天
     * @return
     */
    public static String getMinDate(){

        //获取当前月第一天
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        //设置为1号,当前日期既为本月第一天
        c.set(Calendar.DAY_OF_MONTH,1);
        String first = format.format(c.getTime());
        return first;
    }

    /**
     * 获取本月最后一天
     * @return
     */
    public static String getMaxDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = format.format(ca.getTime());
        return lastDay;
    }

    /**
     * 获取上月第一天
     * @return
     */
    public static String getPrecedingMonthMinDate(){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal_1=Calendar.getInstance();
        cal_1.add(Calendar.MONTH, -1);
        cal_1.set(Calendar.DAY_OF_MONTH,1);
        return format.format(cal_1.getTime());
    }

    /**
     * 获取上月最后一天
     * @return
     */
    public static String getPrecedingMonthMaxDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_MONTH,0);
        String lastDay = format.format(cale.getTime());
        return lastDay;
    }

    /**
     * 获取下月第一天
     * @return
     */
    public static String getLastMonthMinDate(){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal_1=Calendar.getInstance();
        cal_1.add(Calendar.MONTH, 1);
        cal_1.set(Calendar.DAY_OF_MONTH,1);
        return format.format(cal_1.getTime());
    }

    /**
     * 获取下月最后一天
     * @return
     */
    public static String getLastMonthMaxDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_MONTH,0);
        String lastDay = format.format(cale.getTime());
        return lastDay;
    }

    /**
     * 获取昨天
     * @return
     */
    public static String getYesterdayDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.setTime(new Date());
        cale.add(Calendar.DATE,-1);
        String yesterday = format.format(cale.getTime());

        return yesterday;
    }

    /**
     * 获取今天
     * @return
     */
    public static String getTodayDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.setTime(new Date());
        cale.add(Calendar.DATE,0);
        String today = format.format(cale.getTime());
        return today;
    }

    /**
     * 获取明天
     * @return
     */
    public static String getTomorrowDate(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.setTime(date);
        cale.add(Calendar.DATE,1);
        return format.format(cale.getTime());
    }
    /**
     * 获得指定日期的前几天
     * @param specifiedDay
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayBefore(String specifiedDay,Integer severalDays){

        Calendar c = Calendar.getInstance();
        Date date=null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day=c.get(Calendar.DATE);
        c.set(Calendar.DATE,day - severalDays);

        String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }

    /**
     * 获得指定日期的所在周
     * @param day
     * @return
     * @throws Exception
     */
    public static Integer getWeekOfYear(String day){

        Calendar c = Calendar.getInstance();
        Date date= null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);

        int index = c.get(Calendar.WEEK_OF_YEAR);

        return index;
    }

    public static Date getMonthLastDay(String dt) {
        String[] str = dt.split("-");
        // 使用YearMonth类来表示年月
        YearMonth yearMonth1 = YearMonth.of(Integer.parseInt(str[0]), Integer.parseInt(str[1]));
        // 使用LocalDate类获取该年月的最后一天
        LocalDate lastDay1 = yearMonth1.atEndOfMonth();
        return DateUtils.toDate(lastDay1);
    }

    public static Date getBeforeWeekDate(){
        return getBeforeDate(-7);
    }
    public static Date getBeforeDate(int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, amount);
        return calendar.getTime();
    }
    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}
